import React, { useEffect, useState } from "react";
import CertificateAPI from "../api/certificateApi";
import { Certificate } from "../types/Certificate";
import { CdnNode } from "../types/CdnNode";
import { getNodes } from "../api/cdnNodeApi";

const CertificatePage = () => {
  const [certificates, setCertificates] = useState<Certificate[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [showApplyModal, setShowApplyModal] = useState(false); // 新增：申请证书弹窗
  const [nodes, setNodes] = useState<CdnNode[]>([]);
  const [currentCert, setCurrentCert] = useState<Partial<Certificate>>({
    domain: "",
    fullchain: "",
    privkey: "",
  });
  const [applyData, setApplyData] = useState({ domain: "", host: "" }); // 新增：申请证书数据
  const [toast, setToast] = useState<{ message: string; type: "success" | "error" } | null>(null);

  const showToast = (message: string, type: "success" | "error" = "success") => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 3000); // 3秒后自动消失
  };

  // 获取证书列表
  const fetchCertificates = async () => {
    try {
      const data = await CertificateAPI.getAll();
      setCertificates(Array.isArray(data) ? data : []);
    } catch (err) {
      console.error("获取证书列表失败:", err);
      setCertificates([]);
    }
  };

  useEffect(() => {
    fetchCertificates();
    getNodes().then(setNodes).catch(err => console.error("获取节点失败:", err));
  }, []);

  // 新增 / 更新证书
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!currentCert.domain || !currentCert.fullchain || !currentCert.privkey) {
      alert("请填写域名和证书内容");
      return;
    }

    try {
      if (currentCert.id) {
        await CertificateAPI.update(currentCert.id, currentCert);
      } else {
        await CertificateAPI.create(currentCert);
      }

      fetchCertificates();
    } catch (err) {
      console.error("保存证书失败:", err);
      alert("保存证书失败");
    } finally {
      setShowModal(false);
      setCurrentCert({ domain: "", cert: "", fullchain: "", privkey: "" });
    }
  };

  // 申请证书
  const handleApply = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!applyData.domain || !applyData.host) {
      showToast("请填写域名和申请 IP", "error");
      return;
    }

    try {
      await CertificateAPI.apply(applyData);
      showToast("证书申请成功", "success");
      fetchCertificates();
    } catch (err: any) {
      showToast(err.response?.data?.detail || "申请证书失败", "error");
    } finally {
      setShowApplyModal(false);
      setApplyData({ domain: "", host: "" });
    }
  };

  // 删除
  const handleDelete = async (id: number) => {
    if (!window.confirm("确定要删除该证书吗？")) return;
    try {
      await CertificateAPI.delete(id);
      fetchCertificates();
    } catch (err) {
      console.error("删除证书失败:", err);
      alert("删除失败");
    }
  };

  // 编辑
  const handleEdit = (cert: Certificate) => {
    setCurrentCert(cert);
    setShowModal(true);
  };

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
      {/* 消息弹窗 */}
{toast && (
  <div
    className={`
      fixed inset-0 flex items-center justify-center z-50
    `}
  >
    <div
      className={`
        px-8 py-4 rounded-xl shadow-2xl text-white font-semibold text-lg
        ${toast.type === "success" ? "bg-green-600" : "bg-red-600"}
        animate-toast
      `}
    >
      {toast.message}
    </div>
  </div>
)}

<style>
{`
@keyframes toastIn {
  0% { opacity: 0; transform: scale(0.8); }
  60% { opacity: 1; transform: scale(1.05); }
  100% { transform: scale(1); }
}

@keyframes toastShake {
  0%, 100% { transform: translateX(0); }
  20% { transform: translateX(-5px); }
  40% { transform: translateX(5px); }
  60% { transform: translateX(-5px); }
  80% { transform: translateX(5px); }
}

.animate-toast {
  animation: toastIn 0.5s ease forwards, toastShake 0.5s ease 0.5s;
}
`}
</style>



      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">证书管理</h1>
        <div className="space-x-3">
          <button
            className="bg-green-600 text-white py-2 px-5 rounded-lg hover:bg-green-700"
            onClick={() => setShowApplyModal(true)}
          >
            申请证书
          </button>
          <button
            className="bg-blue-600 text-white py-2 px-5 rounded-lg hover:bg-blue-700"
            onClick={() => {
              setCurrentCert({ domain: "", fullchain: "", privkey: "" });
              setShowModal(true);
            }}
          >
            + 新增证书
          </button>
        </div>
      </div>

      {/* 证书列表表格 */}
      <div className="overflow-x-auto rounded-lg shadow">
        <table className="w-full text-sm text-left text-gray-600 dark:text-gray-300">
          <thead className="text-xs uppercase bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300">
            <tr>
              <th className="px-6 py-3">ID</th>
              <th className="px-6 py-3">域名</th>
              <th className="px-6 py-3">Cert（证书）</th>
              <th className="px-6 py-3">Fullchain（完整证书链）</th>
              <th className="px-6 py-3">PrivKey（私钥）</th>
              <th className="px-6 py-3">时效（天）</th>
              <th className="px-6 py-3 text-right">操作</th>
            </tr>
          </thead>
          <tbody>
            {certificates.length > 0 ? (
              certificates.map((cert) => (
                <tr
                  key={cert.id}
                  className="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600"
                >
                  <td className="px-6 py-4">{cert.id}</td>
                  <td className="px-6 py-4">{cert.domain}</td>
                  <td className="px-6 py-4 max-w-xs">
                    <textarea
                      readOnly
                      value={cert.cert || ""}
                      className="w-full px-2 py-1 border rounded-lg resize-none dark:bg-gray-700 dark:text-white overflow-auto"
                      rows={3}
                    />
                  </td>
                  <td className="px-6 py-4 max-w-xs">
                    <textarea
                      readOnly
                      value={cert.fullchain}
                      className="w-full px-2 py-1 border rounded-lg resize-none dark:bg-gray-700 dark:text-white overflow-auto"
                      rows={3}
                    />
                  </td>
                  <td className="px-6 py-4 max-w-xs">
                    <textarea
                      readOnly
                      value={cert.privkey}
                      className="w-full px-2 py-1 border rounded-lg resize-none dark:bg-gray-700 dark:text-white overflow-auto"
                      rows={3}
                    />
                  </td>
                  <td className="px-6 py-4 max-w-xs font-semibold text-center">
                    {(() => {
                      const requestedTime = new Date(cert.requested_at);
                      const diffMs = Date.now() - requestedTime.getTime();
                      const daysPassed = Math.ceil(diffMs / (1000 * 60 * 60 * 24));
                      const remainingDays = 90 - daysPassed;

                      if (remainingDays <= 0) {
                        return <span className="text-gray-500">已过期</span>;
                      } else if (remainingDays < 30) {
                        return <span className="text-red-500">{remainingDays}天</span>;
                      } else {
                        return <span className="text-green-500">{remainingDays}天</span>;
                      }
                    })()}
                  </td>

                  <td className="px-6 py-4 flex justify-end space-x-2">
                    <button
                      className="bg-blue-500 text-white py-1.5 px-3 rounded hover:bg-blue-600"
                      onClick={() => handleEdit(cert)}
                    >
                      编辑
                    </button>
                    <button
                      className="bg-red-500 text-white py-1.5 px-3 rounded hover:bg-red-600"
                      onClick={() => handleDelete(cert.id)}
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={5} className="px-6 py-4 text-center text-gray-500">
                  暂无数据
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* 新增/编辑证书弹窗 */}
      {showModal && (
        <div className="fixed inset-0 flex items-center justify-center z-50">
          <div
            className="absolute inset-0 bg-black bg-opacity-40"
            onClick={() => setShowModal(false)}
          ></div>
          <div className="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-lg z-10 w-full max-w-lg">
            <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-white">
              {currentCert.id ? "编辑证书" : "新增证书"}
            </h2>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-gray-700 dark:text-gray-300 mb-1">域名</label>
                <input
                  type="text"
                  value={currentCert.domain || ""}
                  onChange={(e) =>
                    setCurrentCert({ ...currentCert, domain: e.target.value })
                  }
                  required
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              <div>
                <label className="block text-gray-700 dark:text-gray-300 mb-1">
                  Cert（证书） <span className="text-gray-400 text-sm">(可为空)</span>
                </label>
                <textarea
                  value={currentCert.cert || ""}
                  onChange={(e) =>
                    setCurrentCert({ ...currentCert, cert: e.target.value }) // 修正绑定字段
                  }
                  rows={6}
                  placeholder="可选填写，如果已有 fullchain 可不填"
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white resize-none"
                />
              </div>
              <div>
                <label className="block text-gray-700 dark:text-gray-300 mb-1">Fullchain（完整证书链）</label>
                <textarea
                  value={currentCert.fullchain || ""}
                  onChange={(e) =>
                    setCurrentCert({ ...currentCert, fullchain: e.target.value })
                  }
                  required
                  rows={6}
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white resize-none"
                />
              </div>
              <div>
                <label className="block text-gray-700 dark:text-gray-300 mb-1">PrivKey（私钥）</label>
                <textarea
                  value={currentCert.privkey || ""}
                  onChange={(e) =>
                    setCurrentCert({ ...currentCert, privkey: e.target.value })
                  }
                  required
                  rows={6}
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white resize-none"
                />
              </div>
              <div className="flex justify-end space-x-3 pt-2">
                <button
                  type="button"
                  className="bg-gray-400 text-white py-2 px-4 rounded hover:bg-gray-500"
                  onClick={() => setShowModal(false)}
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="bg-blue-600 text-white py-2 px-4 rounded hover:bg-blue-700"
                >
                  保存
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* 申请证书弹窗 */}
      {showApplyModal && (
        <div className="fixed inset-0 flex items-center justify-center z-50">
          <div
            className="absolute inset-0 bg-black bg-opacity-40"
            onClick={() => setShowApplyModal(false)}
          ></div>
          <div className="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-lg z-10 w-full max-w-md">
            <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-white">
              申请证书
            </h2>
            <p className="text-sm text-red-500 mb-3">
              ⚠️ 请确认：域名 A 记录已指向该 IP，并已开放 80 和 443 端口
            </p>
            <form onSubmit={handleApply} className="space-y-4">
              <div>
                <label className="block text-gray-700 dark:text-gray-300 mb-1">
                  域名
                </label>
                <input
                  type="text"
                  value={applyData.domain}
                  onChange={(e) =>
                    setApplyData({ ...applyData, domain: e.target.value })
                  }
                  required
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              {/* <div>
                <label className="block text-gray-700 dark:text-gray-300 mb-1">
                  申请 IP
                </label>
                <input
                  type="text"
                  value={applyData.host}
                  onChange={(e) =>
                    setApplyData({ ...applyData, host: e.target.value })
                  }
                  required
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div> */}
              <div>
                <label className="block text-gray-700 dark:text-gray-300 mb-1">
                  申请节点
                </label>
                <select
                  value={applyData.host}
                  onChange={(e) =>
                    setApplyData({ ...applyData, host: e.target.value })
                  }
                  required
                  className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 
               bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                >
                  <option value="">请选择节点</option>
                  {nodes.map((node) => (
                    <option key={node.id} value={node.host}>
                      {node.name} ({node.host})
                    </option>
                  ))}
                </select>
              </div>
              <div className="flex justify-end space-x-3 pt-2">
                <button
                  type="button"
                  className="bg-gray-400 text-white py-2 px-4 rounded hover:bg-gray-500"
                  onClick={() => setShowApplyModal(false)}
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="bg-green-600 text-white py-2 px-4 rounded hover:bg-green-700"
                >
                  提交申请
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default CertificatePage;
